﻿using Apewer.Network;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace Apewer.Web
{

    /// <summary>请求。</summary>
    public sealed class MiniRequest : IToJson
    {

        /// <summary>上下文。</summary>
        public MiniContext Context { get; private set; }

        #region connection

        internal bool Http11 = false;

        /// <summary>要求保持连接。</summary>
        public bool KeepAlive { get; internal set; }

        #endregion

        #region headers

        HttpHeaders _headers = new HttpHeaders();

        /// <summary>头部。</summary>
        public HttpHeaders Headers { get => _headers; }

        /// <summary>统一资源定位。</summary>
        public Uri Url { get; internal set; }

        /// <summary>请求方法。</summary>
        public string Method { get; internal set; }

        /// <summary>URL 路径。</summary>
        public string Path { get; internal set; }

        /// <summary>HTTP 协议版本。</summary>
        public string Version { get; internal set; }

        /// <summary>客户端可接受 Brotli 压缩。</summary>
        public bool Brotli { get; internal set; }

        /// <summary>客户端可接受 Gzip 压缩。</summary>
        public bool Gzip { get; internal set; }

        /// <summary>内容长度，单位：字节。</summary>
        public long ContentLength { get => _headers.GetValue("Content-Length").Int64(); }

        #endregion

        #region

        /// <summary>请求体的流。</summary>
        public Stream Body { get => Context.Connection.GetRequestStream(); }

        #endregion

        /// <summary></summary>
        internal MiniRequest(MiniContext context)
        {
            Context = context;
        }

        /// <summary>专用的序列化方法。</summary>
        public Json ToJson()
        {
            var json = new Json();
            json.SetProperty("Method", Method);
            json.SetProperty("Path", Path);
            json.SetProperty("Url", Url?.OriginalString);
            json.SetProperty("Headers", Json.From(Headers));
            return json;
        }

    }

}
